<template>
  <el-config-provider :locale="zhCn">
    <div id="app">
      <router-view />
    </div>
  </el-config-provider>
</template>

<script setup>
import { onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from './store/authStore'
import { dynamicRoutes, GetRoutes } from './utils/api'
import { zhCn } from 'element-plus/es/locales.mjs'
import { ElConfigProvider } from 'element-plus'
import { CheckToken } from './utils/api'

const router = useRouter()
const authStore = useAuthStore()

// 在组件挂载时检查用户的认证状态并执行动态路由渲染
onMounted(async () => {
  // 获取存储的路由路径，如果没有则默认为首页 '/'
  const savedRoute = localStorage.getItem('savedRoute') || '/'

  if (authStore.isAuth && CheckToken()) {
    await GetRoutes()
    // 如果用户已认证，加载动态路由
    await dynamicRoutes(router)
    // 动态路由加载完毕后跳转到之前保存的路由
    router.push(savedRoute)
  } else {
    // 如果没有认证，跳转到登录页
    router.push('/login')
  }
})

// 监听路由变化并保存当前路由到 localStorage
router.afterEach((to, from) => {
  // 保存当前路由路径到 localStorage
  localStorage.setItem('savedRoute', to.fullPath)
})
</script>
